import threading
from lslSender import LSLSender
import numpy as np
import tkinter as tk

use_simulator = 1

channel_num = 32
sample_num_pkg = 10

timer_interval = 0.05

mLSL = LSLSender('dummy')

# 创建一个事件对象，用于控制定时器是否继续运行
stop_event = threading.Event()

def simulator_timer_handler():
    if stop_event.is_set():  # 如果事件被设置为停止，则不执行任务
        return

    e = np.random.randint(0, 65535, (channel_num * sample_num_pkg))
    for i in range(sample_num_pkg):
        # mLSL.send_eeg_mii(e[i * channel_num:i * channel_num + channel_num])
        mLSL.send_bci32(e[i * channel_num:i * channel_num + channel_num])

    # 1秒后重新启动定时器，确保每秒执行一次
    if not stop_event.is_set():  # 只有在未停止时才启动新的定时器
        simulator_timer = threading.Timer(timer_interval, simulator_timer_handler)  # 1秒后执行
        simulator_timer.start()
    # print("send data")

def on_closing():
    stop_event.set()  # 设置事件为停止状态，停止定时器
    root.quit()  # 关闭窗口时退出程序

# 创建一个Tkinter窗口
root = tk.Tk()
root.title("Simulation Running")
root.geometry("300x100")

# 添加一个标签，显示模拟正在运行
label = tk.Label(root, text="Simulation is running... Press Close to stop.")
label.pack(pady=20)

# 当关闭窗口时触发
root.protocol("WM_DELETE_WINDOW", on_closing)

# 启动模拟器，第一次启动定时器
simulator_timer_handler()

# 启动GUI
root.mainloop()
